<template>
  <el-drawer
    size="80%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    :model-value="checkDialog"
    @close="onCancel"
  >
    <template #header>
      <div class="header">
        <span class="text">审核配件</span>
        <HStatus type="warning" :height="20">待审核</HStatus>
      </div>
    </template>
    <div v-loading="saveLoading || getDetailLoading" element-loading-text="加载中...">
      <p v-if="detailData" class="top_no"
        >配件编号：{{ detailData.code }} &nbsp; 工单单号：{{ detailData.workNo }}</p
      >
      <h4 class="title_top">基本信息</h4>
      <div v-if="detailData" class="table-detail">
        <el-form label-position="right" label-width="100">
          <div class="form_sction">
            <!-- 申请类型 -->
            <el-form-item label="申请类型:">
              <span>{{ options6[detailData.type - 1].name }}</span>
            </el-form-item>

            <!-- 服务商配件类型 -->
            <el-form-item v-if="detailData.type == 2" label="服务商配件类型:">
              <span>{{ options3[detailData.networkSpareType - 1].name }}</span>
            </el-form-item>
          </div>
          <el-row>
            <el-col :md="8">
              <!-- 收货地址类型 -->
              <el-form-item label="收货地址类型:">
                <el-select
                  v-model="dataList.receiptAddrType"
                  style="width: 200px"
                  clearable
                  placeholder="收货地址类型"
                  @change="changeAddrType"
                >
                  <el-option label="工单客户" :value="1" />
                  <el-option label="服务商" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="8">
              <!-- 收货人姓名 -->
              <el-form-item label="收货人姓名:">
                <el-input
                  v-model="dataList.receiptName"
                  style="width: 200px"
                  clearable
                  placeholder="收货人姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :md="8">
              <!-- 收货人手机号 -->
              <el-form-item label="收货人手机号:">
                <el-input
                  v-model="dataList.receiptPhone"
                  :maxlength="11"
                  style="width: 200px"
                  clearable
                  placeholder="收货人手机号"
                  @input="dataList.receiptPhone = dataList.receiptPhone.replace(/\D/g, '')"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :lg="8" :xs="24">
              <!-- 收货人地址 -->
              <el-form-item label="收货人地址:">
                <div class="singleAddress">
                  <SingleAddress ref="addrsDom" :address="addrs" />
                </div>
              </el-form-item>

              <!-- 旧件处理方式 -->
              <el-form-item label="旧件处理方式:">
                <el-select
                  v-model="dataList.oldCopeWay"
                  style="width: 200px"
                  placeholder="旧件处理方式"
                  @change="changeoldCopeWay"
                >
                  <el-option label="废弃" :value="1" />
                  <el-option label="旧件退回" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xs="24">
              <!-- 详细地址 -->
              <el-form-item label="详细地址:">
                <el-input
                  v-model="dataList.receiptAddress"
                  :rows="2"
                  style="width: 200px"
                  clearable
                  maxlength="200"
                  placeholder="收货人详细地址"
                  show-word-limit
                  size="small"
                  type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="dataList.oldCopeWay == 2">
            <el-col :lg="8" :xs="24">
              <!-- 退回仓库 -->
              <el-form-item label="退回仓库:">
                <el-select
                  v-model="dataList.storeId"
                  :loading="getReturnWareHouseOptionsLoading"
                  :filter-method="handleGetReturnWareHouseOptions"
                  style="width: 200px"
                  filterable
                  placeholder="请选择仓库"
                  remote-show-suffix
                  @change="changeoldCopeWay(1)"
                >
                  <el-option
                    v-for="item in returnWareHouseOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handleChangeReturnWareHouse(item)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xs="24">
              <!-- 退回仓位 -->
              <el-form-item
                v-if="isEnableStorePosition(dataList.storeId, returnWareHouseOptions)"
                label="退回仓位:"
              >
                <el-select
                  v-model="dataList.storePositionId"
                  :disabled="!isEnableStorePosition(dataList.storeId, returnWareHouseOptions)"
                  :loading="loading"
                  :filter-method="(val: string) => handleGetStorePositionOptions(val, dataList.storeId)"
                  filterable
                  placeholder="退回仓位"
                  remote-show-suffix
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in sotrePositionOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="dataList.oldCopeWay == 2 && dataList.storeId" class="form_sction">
            <span class="look_text">姓名：{{ dataList.oldReceiptName }}</span>
            <span class="look_text">手机号：{{ dataList.oldReceiptPhone }}</span>
            <span class="look_text"
              >旧件收货地址：{{
                dataList.oldReceiptProvince +
                dataList.oldReceiptCity +
                dataList.oldReceiptArea +
                dataList.oldReceiptTown +
                dataList.oldReceiptAddress
              }}
            </span>
          </el-form-item>
        </el-form>
      </div>
      <div class="table">
        <el-table
          :border="true"
          :data="dataList.workSpareMaterials"
          resizable
          stripe
          max-height="500"
          v-loading="getListDetailLoading"
        >
          <el-table-column fixed="left" label="序号" min-width="50" show-overflow-tooltip>
            <template v-slot="i">
              {{ i.$index + 1 }}
            </template>
          </el-table-column>
          <!-- 审核状态 -->
          <el-table-column label="审核状态" show-overflow-tooltip width="120">
            <template #default="scope">
              <el-select v-model="scope.row.status" filterable placeholder="审核状态">
                <el-option label="已通过" :value="2" />
                <el-option label="已驳回" :value="3" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 收支类型 -->
          <el-table-column label="收支类型" show-overflow-tooltip width="150">
            <template #default="scope">
              <el-select
                @change="handleChangeIncomeOrPayType(scope.$index)"
                v-model="scope.row.type"
                placeholder="收支类型"
              >
                <el-option label="商家承担" :value="1" />
                <el-option label="平台承担" :value="2" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 申请的配件物料 -->
          <el-table-column label="申请的配件物料" show-overflow-tooltip width="240">
            <template v-slot="i">
              {{ i.row.applySpareModel }}、{{ i.row.applySpareSpec }}、{{
                i.row.applySpareSpecCode
              }}
            </template>
          </el-table-column>

          <!-- 配件名称 -->
          <el-table-column label="配件名称" width="240">
            <template #default="scope">
              <el-select
                v-model="scope.row.spareId"
                :loading="loading2"
                :filter-method="handleGetPartOptions"
                filterable
                placeholder="请选择"
                remote-show-suffix
                @change="(id: string) => handleChangePart(id, scope.$index)"
              >
                <el-option
                  v-for="item in partOptions"
                  :key="item.id"
                  :label="`${item.model}`"
                  :value="item.id"
                  @click="handlePartOptionClick(item, scope.$index)"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 规格 -->
          <el-table-column label="规格" width="180">
            <template #default="scope">
              <el-select
                v-model="scope.row.specId"
                :loading="getPartSpecOptionsLoading"
                :filter-method="(val: string) => handleGetPartSpecOptions(val, scope.row.spareId, scope.$index)"
                filterable
                placeholder="请选择"
                remote-show-suffix
                @change="(id: any) => handlePartSpecClick(id, scope.$index)"
              >
                <el-option
                  v-for="item in scope.row.partSpecOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                  @click="handlePartSpecClick(item, scope.$index)"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 规格编码 -->
          <el-table-column label="规格编码" width="180" prop="model">
            <template #default="scope">
              <el-input :value="scope.row.checkSpareSpecCode" disabled />
            </template>
          </el-table-column>

          <!-- 仓库 -->
          <template v-if="!(detailData && detailData.networkSpareType === 3)">
            <el-table-column label="仓库" width="180">
              <template #default="scope">
                <el-select
                  v-model="scope.row.storeId"
                  :loading="loading"
                  :filter-method="(val: string) => handleGetReturnWareHouseOptions(val)"
                  filterable
                  placeholder="请选择"
                  remote
                  remote-show-suffix
                  @change="changeSeleStoreId('', scope.row, scope.$index)"
                >
                  <el-option
                    v-for="item in returnWareHouseOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 仓位 -->
            <el-table-column label="仓位" width="120">
              <template #default="scope">
                <el-select
                  v-model="scope.row.storePositionId"
                  :disabled="!isEnableStorePosition(scope.row.storeId, returnWareHouseOptions)"
                  :loading="loading"
                  :filter-method="(val: string) => handleGetTableStorePositionOptions(val, scope.row.storeId, scope.$index)"
                  filterable
                  placeholder="请选择"
                  remote-show-suffix
                  @change="changeSelestorePositionId(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="item in scope.row.storePositionOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 即时库存 -->
            <el-table-column label="即时库存" width="180">
              <template #default="scope">
                <span>{{ scope.row.systemStock }}</span>
              </template>
            </el-table-column>
          </template>

          <!-- 物料质保状态 -->
          <el-table-column label="物料质保状态" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.overinsured"
                clearable
                filterable
                placeholder="物料质保状态"
                @change="(val: boolean) => handleChangeOverinsured(val, scope.$index)"
              >
                <el-option label="保内" :value="false" />
                <el-option label="保外" :value="true" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 申请数量 -->
          <!-- <el-table-column label="申请数量" show-overflow-tooltip width="90">
            <template #default="scope">
              <el-input
                v-model="scope.row.qty"
                clearable
                placeholder="数量"
                @input="scope.row.qty = scope.row.qty.replace(/\D/g, '')"
              />
            </template>
          </el-table-column> -->

          <!-- 向服务商支付费用单价 -->
          <el-table-column label="支付服务商费用" width="150">
            <template #default="scope">
              <el-input
                clearable
                v-model="scope.row.payNetworkPrice"
                @keyup="(e: Event) => handlePayNetworkPricePriceInput(e, scope.$index)"
                style="border-radius: 2px"
              >
                <template #prepend>￥</template>
              </el-input>
            </template>
          </el-table-column>

          <!-- 收取商家费用单价 -->
          <el-table-column label="收取商家费用" width="140">
            <template #default="scope">
              <el-input
                clearable
                v-model="scope.row.receiveFactoryPrice"
                @keyup="(e: Event) => handleReceiveFactoryPriceInput(e, scope.$index)"
                style="border-radius: 2px"
              >
                <template #prepend>￥</template>
              </el-input>
            </template>
          </el-table-column>

          <!-- 平台承担费用单价 -->
          <el-table-column label="平台承担费用单价" width="140">
            <template #default="scope">
              <el-input
                clearable
                v-model="scope.row.price"
                @keyup="(e: Event) => handlePriceInput(e, scope.$index)"
                style="border-radius: 2px"
              >
                <template #prepend>￥</template>
              </el-input>
            </template>
          </el-table-column>

          <!-- 备注 -->
          <el-table-column label="备注" max-width="150" min-width="140" show-overflow-tooltip>
            <template #default="scope">
              <el-input v-model="scope.row.remark" clearable placeholder="填写备注" />
            </template>
          </el-table-column>

          <!-- 附件 -->
          <el-table-column :width="460" label="附件(最多上传8个)">
            <template #default="scope">
              <div class="updata_pic">
                <el-dropdown v-for="(img, imgIndex) in scope.row.images" :key="imgIndex">
                  <el-image
                    class="img"
                    style="width: 40px; height: 40px"
                    :src="img.image"
                    :initial-index="imgIndex"
                    :preview-src-list="scope.row.images.map((item) => item.image)"
                    fit="scale-down"
                    preview-teleported
                  />
                  <template #dropdown v-if="!img.id">
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleDelFile(scope.$index, imgIndex)"
                        >删除</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
                <el-upload
                  :auto-upload="false"
                  :on-change="(file) => getProImages(file, scope.$index)"
                  :show-file-list="false"
                  accept="image/*"
                  action="#"
                  list-type="picture-card"
                  multiple
                  v-if="scope.row.images.length < 8"
                >
                  <div class="plus_add">
                    <el-icon size="12">
                      <Plus />
                    </el-icon>
                  </div>
                </el-upload>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer_remark">
        <el-form-item label="审核备注">
          <el-input
            v-model="dataList.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            class="w_input"
            clearable
            maxlength="200"
            placeholder="填写备注信息"
            show-word-limit
            size="small"
            type="textarea"
          />
        </el-form-item>
      </div>
    </div>

    <template #footer>
      <div class="btns flex-justify-end" style="gap: 10px">
        <HButton
          is-modal
          type="primary"
          :disabled="$route.query.isArchive == 'true'"
          @click="onSave"
          >保存</HButton
        >
        <HButton isModal @click="onCancel">取消</HButton>
      </div>
    </template>
  </el-drawer>

  <HModal v-model="dialogVisible" title="查看附件">
    <iframe :src="`${dialogImageUrl}`" frameborder="0" style="height: 660px; width: 100%"></iframe>
  </HModal>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, ref, toRefs, watch } from 'vue'
  import { sparePageSelect, spareSpecPageSelect } from '@/api/code'
  import {
    getGoodsStock,
    storeEmpAddressPageSelect,
    storePageSelect,
    storePositionPageSelect,
  } from '@/api/store'
  import {
    checkOrderSpare,
    getBeforeCheckOrderSpareDetail,
    getOrderNetworkAddress,
    getOrderSpareMaterial,
    getWorkUserAddress,
  } from '@/api/parts'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { ElMessage, UploadFile, UploadRawFile } from 'element-plus'
  import { checkNum, keepPartInteger } from '@/utils/validate'
  import { Plus } from '@element-plus/icons-vue'
  import _ from 'lodash'
  import {
    PartOptions,
    PartSpecOptions,
    ReturnWareHouseOptions,
    StorePositionOptions,
  } from './types'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    checkDialog: Boolean,
    partsId: String,
    workId: [String, Array],
  })

  /**
   * 获取配件详情
   * @param index
   */
  const getSpareDetail = (index: number) => {
    return dataList.value.workSpareMaterials[index]
  }

  // 质保状态更新事件
  const handleChangeOverinsured = (val: boolean, index: number) => {
    const partSpec = getSpareDetail(index).partSpecOptions.find(
      (item) => item.specSkuCode === getSpareDetail(index).checkSpareSpecCode,
    )
    const price = val ? partSpec.overPrice : partSpec.price

    /**
     * 收支类型是商家承担
     * 将规格的金额填充到收取商家费用
     */
    if (getSpareDetail(index).type === 1 && !Number(getSpareDetail(index).receiveFactoryPrice)) {
      dataList.value.workSpareMaterials[index].receiveFactoryPrice = `${price}`
    }

    /**
     * 收支类型是商家承担
     * 将规格的金额填充到平台承担费用
     */
    if (getSpareDetail(index).type === 2 && !Number(getSpareDetail(index).price)) {
      dataList.value.workSpareMaterials[index].price = `${price}`
    }
  }

  /**
   * 收支类型更新事件
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangeIncomeOrPayType = (index: number) => {
    // 提取费用项目的金额
    let price = 0
    if (dataList.value.workSpareMaterials[index].specId) {
      const feeProject = getSpareDetail(index).partSpecOptions.find(
        (module) => module.id === getSpareDetail(index).specId,
      )
      price = getSpareDetail(index).overinsured ? feeProject.overPrice : feeProject.price
    }

    /**
     * 收支类型是商家承担
     * 将费用项目的金额填充到收取商家费用
     */
    if (getSpareDetail(index).type === 1 && !Number(getSpareDetail(index).receiveFactoryPrice)) {
      dataList.value.workSpareMaterials[index].receiveFactoryPrice = `${price}`
    }

    /**
     * 收支类型是平台承担
     * 将费用项目的金额填充到平台承担费用
     */
    if (getSpareDetail(index).type === 2 && !Number(getSpareDetail(index).price)) {
      dataList.value.workSpareMaterials[index].price = `${price}`
    }
  }

  const { checkDialog, partsId, workId } = toRefs(props)
  const dialogVisible = ref(false)
  const dialogImageUrl = ref(null)

  // 仓库下拉选项
  const returnWareHouseOptions = ref<Array<ReturnWareHouseOptions>>([])

  const loading = ref(false)
  const loading2 = ref(false)
  const emits = defineEmits(['assign-dialog', 'update-list'])

  // 服务商配件类型
  const options3 = [
    { name: '服务商-外部仓配件', value: 1 },
    { name: '工程师-外部仓配件', value: 2 },
    {
      name: '自购配件',
      value: 3,
    },
  ]
  // 申请类型
  const options6 = [
    { name: '平台配件', value: 1 },
    { name: '外部配件', value: 2 },
  ]
  let dataList = ref({
    id: null, //工单配件ID
    oldCopeWay: 2, //旧件处理方式：1-废弃，2-旧件退回,示例值(2)
    oldReceiptAddress: '', //旧件收货人详细地址
    oldReceiptArea: '', //旧件收货地址-县/区
    oldReceiptCity: '', //旧件收货地址-市
    oldReceiptName: '', //旧件收货人姓名
    oldReceiptPhone: '', //旧件收货人手机号
    oldReceiptProvince: '', //旧件收货地址-省
    oldReceiptTown: '', //旧件收货地址-镇
    receiptAddrType: null, //收货地址类型：1-工单客户地址，2-服务商地址
    receiptAddress: '', //收货人详细地址
    receiptArea: '', //收货地址-县/区
    receiptCity: '', //收货地址-市
    receiptName: '', //收货人姓名
    receiptPhone: '', //收货人手机号
    receiptProvince: '', //收货地址-省
    receiptTown: '', //收货地址-镇
    remark: '', //备注
    storeId: null, //旧件退回仓库ID
    storePositionId: null, // 旧件退回仓库仓位ID
    userOrNetworkId: null, //客户/服务商ID
    workSpareMaterials: [
      //工单配件物料
      {
        delImageIds: [], //删除的工单费用图片对象ID
        id: null, //配件物料ID
        images: [
          {
            id: 0,
            image: '',
            file: null,
          },
        ],
        overinsured: false, //质保状态：false-保内，true-保外
        price: '0', // 平台承担费用
        qty: 1, //配件物料数量,示例值(1)
        remark: '', //备注
        spareId: null, //配件ID
        specId: null, //配件规格ID
        status: 2, //配件物料审核状态：2-已通过，3-已驳回,示例值(2)
        storeId: null, //仓库ID
        storePositionId: null, //仓位id
        type: 1, //	结算类型：1-向服务商收取，2-向服务商支付，3-向客户收取，4-向客户支付,示例值(1)
        spareSelect: [], //配件
        spareSpecSelect: [], //规格
        checkSpareSpec: '',
        checkSpareSpecCode: '',
        storePageSelect: [], //仓库下拉列表
        storePositionPageSelect: [], //仓位下拉列表
        checkSpareModel: '',
        systemStock: 0, //即时库存
        receiveFactoryPrice: '0', // 收取商家费用
        payNetworkPrice: '0', // 向服务商支付费用
        partSpecOptions: [],
        storePositionOptions: [],
      },
    ],
  })
  const detailData = ref(null) //详情
  const addrsDom = ref()
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 获取退回仓库下拉选项请求参数
  const getReturnWareHouseOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  /**
   * 获取退回仓库下拉选项
   */
  const handleGetReturnWareHouseOptions = _.throttle((query: string) => {
    if (getReturnWareHouseOptionsParam.value.name !== query) {
      getReturnWareHouseOptionsParam.value.name = query
      getReturnWareHouseOptionsFn()
    }
  }, 500)

  // 获取退回仓库下拉选项加载
  const getReturnWareHouseOptionsLoading = ref(false)

  /**
   * 获取退回仓库下拉选项方法
   */
  const getReturnWareHouseOptionsFn = async () => {
    getReturnWareHouseOptionsLoading.value = true
    let networkSpareType = 0
    const res = await storeEmpAddressPageSelect(
      getReturnWareHouseOptionsParam.value,
      networkSpareType,
    )
    if (res.data.success) {
      returnWareHouseOptions.value = res.data.data.rows
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 2000,
          type: 'error',
        })
    }
    getReturnWareHouseOptionsLoading.value = false
  }

  /**
   * 退回仓库下拉选项点击事件
   * @param {object} item - 人员、地址、仓库信息
   */
  const handleChangeReturnWareHouse = (item: ReturnWareHouseOptions) => {
    dataList.value.oldReceiptName = item.userName
    dataList.value.oldReceiptPhone = item.phone
    dataList.value.oldReceiptAddress = item.address
    dataList.value.oldReceiptProvince = item.province
    dataList.value.oldReceiptCity = item.city
    dataList.value.oldReceiptArea = item.area
    dataList.value.oldReceiptTown = item.town
    dataList.value.storePositionId = null
    sotrePositionOptions.value = []
    if (isEnableStorePosition(item.id, returnWareHouseOptions.value)) {
      getStorePositionOptionsFn('', item.id)
    }
  }

  // 获取仓位下拉选项请求关键字
  const getStorePositionOptionsKeyword = ref('')

  // 仓位下拉选项
  const sotrePositionOptions = ref<Array<StorePositionOptions>>([])

  /**
   * 获取仓位下拉选项
   */
  const handleGetStorePositionOptions = _.throttle((query: string, id: string) => {
    if (getStorePositionOptionsKeyword.value !== query) {
      getStorePositionOptionsKeyword.value = query
      getStorePositionOptionsFn(getStorePositionOptionsKeyword.value, id)
    }
  }, 500)

  /**
   * 获取仓位下拉选项方法
   * @param {string} query - 关键字
   * @param {string} id - 仓库id
   */
  const getStorePositionOptionsFn = async (query: string, id: string) => {
    if (id) {
      const data = {
        limit: 0,
        page: 0,
        name: query,
      }
      const res = await storePositionPageSelect(data, id)
      sotrePositionOptions.value = res.data.data.rows
    }
  }

  // 获取表格的仓位下拉选项关键字
  const getTableStorePositionOptionsKeyword = ref('')

  /**
   * 获取表格的仓位下拉选项
   */
  const handleGetTableStorePositionOptions = _.throttle(
    (query: string, id: string, index: number) => {
      if (getTableStorePositionOptionsKeyword.value !== query) {
        getTableStorePositionOptionsKeyword.value = query
        getTableStorePositionOptionsFn(query, id, index)
      }
    },
    500,
  )

  /**
   * 获取表格的仓位下拉选项方法
   * @param {string} query - 关键字
   * @param {string} id - 仓库id
   * @param {number} index - 操作的表格行的索引
   */
  const getTableStorePositionOptionsFn = async (query: string, id: string, index: number) => {
    const param = {
      name: query,
      limit: 0,
      page: 0,
    }
    const res = await storePositionPageSelect(param, id)
    dataList.value.workSpareMaterials[index].storePositionOptions = res.data.data.rows
  }

  //仓库下拉变化
  const changeSeleStoreId = (
    val: string,
    row: (typeof dataList.value.workSpareMaterials)[0],
    index: number,
  ) => {
    row.storePositionId = null
    // 判断是否启用仓位
    if (isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
      getTableStorePositionOptionsFn(val, row.storeId, index)
    } else {
      changeSelestorePositionId(row, index)
    }
  }

  // 仓位下拉变化
  const changeSelestorePositionId = (
    row: (typeof dataList.value.workSpareMaterials)[0],
    index: null | number = null,
  ) => {
    if (row.spareId && row.specId && row.storeId) {
      let data = {
        goodsId: row.spareId, //商品ID
        goodsSpecId: row.specId, //商品规格ID
        storeId: row.storeId, //仓库ID
        storePositionId: row.storePositionId, //仓库仓位ID，当仓库启用仓位时，此字段必传
        type: 2, //商品类型：1-成品，2-配件
      }
      dataList.value.workSpareMaterials[index].systemStock = 0
      if (isEnableStorePosition(row.storeId, returnWareHouseOptions.value)) {
        data.storePositionId = row.storePositionId
      }
      getGoodsStock(data).then((res) => {
        if (res) {
          if (res.data.code === 20000) {
            dataList.value.workSpareMaterials[index].systemStock = res.data.data.row.systemStock
          }
        }
      })
    }
  }

  /**
   * 判断是否启用仓位
   * @param id
   * @param storePositions
   */
  const isEnableStorePosition = (id: string, storePositions: Array<ReturnWareHouseOptions>) => {
    if (storePositions.length <= 0) {
      return false
    }

    const storePosition = storePositions.find((item) => item.id === id)
    if (!storePosition) {
      return false
    }
    return storePosition.enableStorePosition
  }

  // 地址类型变化
  const changeAddrType = (val) => {
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        dataList.value.receiptName = ''
        dataList.value.receiptPhone = ''
        dataList.value.receiptAddress = ''
        dataList.value.receiptProvince = ''
        dataList.value.receiptCity = ''
        dataList.value.receiptArea = ''
        dataList.value.receiptTown = ''
        addrs.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        addrsDom.value.clearSelectAddr()
        break
    }
  }
  // 旧件处理方式变化
  const changeoldCopeWay = (val) => {
    switch (val) {
      case 2:
        break
      default:
        dataList.value.oldReceiptName = ''
        dataList.value.oldReceiptPhone = ''
        dataList.value.oldReceiptAddress = ''
        dataList.value.oldReceiptProvince = ''
        dataList.value.oldReceiptCity = ''
        dataList.value.oldReceiptArea = ''
        dataList.value.oldReceiptTown = ''
        break
    }
  }
  // 获取用户地址
  const getWorkUserAddressData = async () => {
    const res = await getWorkUserAddress(workId.value)
    if (res.data.success) {
      dataList.value.userOrNetworkId = res.data.data.row.id
      dataList.value.receiptName = res.data.data.row.name
      dataList.value.receiptPhone = res.data.data.row.phone
      dataList.value.receiptAddress = res.data.data.row.address
      dataList.value.receiptProvince = res.data.data.row.province
      dataList.value.receiptCity = res.data.data.row.city
      dataList.value.receiptArea = res.data.data.row.area
      dataList.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: dataList.value.receiptProvince,
        city: dataList.value.receiptCity,
        area: dataList.value.receiptArea,
        town: dataList.value.receiptTown,
      }
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 2000,
          type: 'error',
        })
    }
  }
  // 获取服务商地址
  const getOrderNetworkAddressData = async () => {
    const res = await getOrderNetworkAddress(workId.value)
    if (res.data.success) {
      dataList.value.userOrNetworkId = res.data.data.row.id
      dataList.value.receiptName = res.data.data.row.name
      dataList.value.receiptPhone = res.data.data.row.phone
      dataList.value.receiptAddress = res.data.data.row.address
      dataList.value.receiptProvince = res.data.data.row.province
      dataList.value.receiptCity = res.data.data.row.city
      dataList.value.receiptArea = res.data.data.row.area
      dataList.value.receiptTown = res.data.data.row.town
      addrs.value = {
        province: dataList.value.receiptProvince,
        city: dataList.value.receiptCity,
        area: dataList.value.receiptArea,
        town: dataList.value.receiptTown,
      }
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 2000,
          type: 'error',
        })
    }
  }

  // 获取配件下拉选项请求参数
  const getPartOptionsKeyword = ref('')

  // 配件下拉选项
  const partOptions = ref<Array<PartOptions>>([])

  // 获取配件下拉选项加载
  const getPartOptionsLoading = ref(false)

  /**
   * 获取配件下拉选项
   */
  const handleGetPartOptions = _.throttle((query: string) => {
    if (getPartOptionsKeyword.value !== query) {
      getPartOptionsKeyword.value = query
      getPartOptionsFn()
    }
  }, 500)

  /**
   * 获取下拉选项方法
   */
  const getPartOptionsFn = async () => {
    getPartOptionsLoading.value = true
    const data = {
      limit: 0,
      page: 0,
      name: getPartOptionsKeyword.value,
    }
    const res = await sparePageSelect(data)
    partOptions.value = res.data.data.rows
    getPartOptionsLoading.value = false
  }

  /**
   * 配件下拉选项点击事件
   * @param {object} val - 配件信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartOptionClick = (val: PartOptions, index: number) => {
    dataList.value.workSpareMaterials[index].checkSpareModel = val.model
  }

  /**
   * 配件选择事件
   * @param {string} id - 配件id
   * @param {number} index - 操作的表格行的索引
   */
  const handleChangePart = (id: string, index: number) => {
    dataList.value.workSpareMaterials[index].specId = null
    dataList.value.workSpareMaterials[index].checkSpareSpecCode = ''
    dataList.value.workSpareMaterials[index].checkSpareSpec = ''
    dataList.value.workSpareMaterials[index].spareSpecSelect = []
    if (id) {
      getPartSpecOptionsFn('', id, index)
    }
  }

  // 获取配件规格下拉选项加载
  const getPartSpecOptionsLoading = ref(false)

  // 获取配件规格关键字
  const getPartSpecOptionsKeyword = ref('')

  /**
   * 获取规格下拉选项
   */
  const handleGetPartSpecOptions = _.throttle((query: string, id: string, index: number) => {
    if (!id || query === getPartSpecOptionsKeyword.value) {
      return
    }
    getPartSpecOptionsKeyword.value = query
    getPartSpecOptionsFn(getPartSpecOptionsKeyword.value, id, index)
  }, 500)

  /**
   * 获取配件规格下拉选项方法
   * @param {string} keyword - 关键字
   * @param {string} id - 配件id
   * @param {number} index - 操作的行的索引
   */
  const getPartSpecOptionsFn = async (keyword: string, id: string, index: number) => {
    getPartSpecOptionsLoading.value = true
    const data = {
      limit: 0,
      page: 0,
      name: keyword,
    }
    const res = await spareSpecPageSelect(data, id)
    dataList.value.workSpareMaterials[index].partSpecOptions = res.data.data.rows
    getPartSpecOptionsLoading.value = false
  }

  // 仓库下拉数据
  const getstorePageSelect = async (val: string, index) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    let networkSpareType = null
    if (detailData.value?.type == 1) {
      networkSpareType = 0
    } else {
      networkSpareType = detailData.value?.networkSpareType
    }
    const res = await storePageSelect(data, networkSpareType)
    if (res) {
      dataList.value.workSpareMaterials[index].storePageSelect = res.data.data.rows
      dataList.value.workSpareMaterials[index].storePositionId = null
    }
  }

  // 保存加载
  const saveLoading = ref(false)

  // 保存
  async function onSave() {
    if (dataList.value.oldCopeWay == null) {
      dataList.value.oldCopeWay = 0
    } else if (dataList.value.oldCopeWay == 2) {
      if (dataList.value.workSpareMaterials.some((o) => o.status == 2)) {
        if (!dataList.value.storeId) {
          ElMessage({
            message: '请选择退回的仓库！',
            type: 'error',
            duration: 3000,
          })
          return
        }
      }
    }
    if (dataList.value.workSpareMaterials.some((o) => o.status == 1)) {
      ElMessage({
        message: '工单配件存在未审核的配件数据，请审核后重新提交',
        type: 'error',
        duration: 3000,
      })
      return
    }
    for (const key in dataList.value.workSpareMaterials) {
      let imgobj = dataList.value.workSpareMaterials[key]
      if (imgobj.status == 2) {
        // 3自购备件
        if (detailData.value.networkSpareType != 3) {
          if (!imgobj.storeId) {
            ElMessage({
              message: '请选择配件仓库',
              type: 'error',
              duration: 3000,
            })
            return
          }
          if (isEnableStorePosition(imgobj.storeId, returnWareHouseOptions.value)) {
            if (!imgobj.storePositionId) {
              ElMessage({
                message: '请选择配件仓位',
                type: 'error',
                duration: 3000,
              })
              return
            }
          }
        }
      }

      saveLoading.value = true
      const __images: Array<{ file: UploadRawFile }> = imgobj.images.map((item) => item.file)
      if (__images.length > 0) {
        const res = await orderAnnexUpload(__images)
        dataList.value.workSpareMaterials[key].images = res.data.data.rows.map((item) => {
          return { id: null, image: item }
        })
      }
    }
    /**
     * 先用Partial<typeof item>将所有属性都变成可选属性
     * 然后再删除规格下拉选项属性
     * 最后再使用Required<typeof __item>将所有属性变成必选属性
     * 如果直接删除会引起typescript的报错
     * 这种处理方式不好，应该使用接口进行类型声明，这样就不用这么麻烦，等后面改到再优化
     */
    dataList.value.workSpareMaterials = dataList.value.workSpareMaterials.map((item) => {
      const __item: Partial<typeof item> = _.cloneDeep(item)
      delete __item.partSpecOptions
      delete __item.storePositionOptions
      return __item as Required<typeof __item>
    })
    const checkResult = await checkOrderSpare(dataList.value)
    if (checkResult.data.success) {
      ElMessage({
        showClose: true,
        message: checkResult.data.message,
        type: 'success',
        offset: 200,
      })
      emits('update-list')
      onCancel()
    } else {
      ElMessage({
        showClose: true,
        message: checkResult.data.message,
        duration: 4000,
        type: 'error',
      })
    }
    saveLoading.value = false
  }

  // 获取详情加载
  const getDetailLoading = ref(false)

  /**
   * 获取详情
   * @param {string} id - 配件id
   */
  const getBeforeCheckOrderSpareDetailInfo = async (id: string) => {
    getDetailLoading.value = true
    const res = await getBeforeCheckOrderSpareDetail(id)
    if (res.data.success) {
      detailData.value = res.data.data.row
      dataList.value = { ...dataList.value, ...detailData.value }
      if (dataList.value.oldCopeWay == 0) {
        dataList.value.oldCopeWay = 2
        await getReturnWareHouseOptionsFn()
        await getPartOptionsFn()
      }
      getDetailLoading.value = false
      setTimeout(async () => {
        await nextTick(async () => {
          if (dataList.value.receiptAddrType == 1) {
            await getWorkUserAddressData()
          } else if (dataList.value.receiptAddrType == 2) await getOrderNetworkAddressData()
        })
      }, 500)
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 4000,
          offset: 200,
          type: 'error',
        })
      getDetailLoading.value = false
    }
  }

  // 获取列表详情加载
  const getListDetailLoading = ref(false)

  /**
   * 获取列表详情
   */
  const getOrderSpareMaterialList = async (id: string) => {
    getListDetailLoading.value = true
    const orderSpareMaterial = await getOrderSpareMaterial(id)
    if (orderSpareMaterial.data.success) {
      dataList.value.workSpareMaterials = orderSpareMaterial.data.data.rows
      for (let i = 0; i < orderSpareMaterial.data.data.rows.length; i++) {
        dataList.value.workSpareMaterials[i].status =
          orderSpareMaterial.data.data.rows[i].status == 1
            ? 2
            : orderSpareMaterial.data.data.rows[i].status
        if (orderSpareMaterial.data.data.rows[i].storeId == 0) {
          dataList.value.workSpareMaterials[i].storeId = null
        }

        if (orderSpareMaterial.data.data.rows[i].spareId != 0) {
          await getPartOptionsFn()
          await getPartSpecOptionsFn('', orderSpareMaterial.data.data.rows[i].spareId, i)
          dataList.value.workSpareMaterials[i].checkSpareSpec =
            orderSpareMaterial.data.data.rows[i].applySpareSpec
          dataList.value.workSpareMaterials[i].checkSpareSpecCode =
            orderSpareMaterial.data.data.rows[i].applySpareSpecCode
        } else {
          dataList.value.workSpareMaterials[i].spareId = null
          dataList.value.workSpareMaterials[i].specId = null
          await getPartOptionsFn()
          await getPartSpecOptionsFn('', orderSpareMaterial.data.data.rows[i].spareId, 0)
        }
        if (detailData.value.networkSpareType != 3) {
          await getstorePageSelect('', i)
        }
      }
    } else {
      ElMessage({
        showClose: true,
        message: orderSpareMaterial.data.message,
        duration: 4000,
        type: 'error',
      })
    }
    getListDetailLoading.value = false
  }

  /**
   * 配件规格点击事件
   * @param {object} val - 配件规格信息
   * @param {number} index - 操作的表格行的索引
   */
  const handlePartSpecClick = (val: PartSpecOptions, index: number) => {
    if (Object.prototype.toString.call(val) === '[object Object]') {
      dataList.value.workSpareMaterials[index].checkSpareSpec = val.name
      dataList.value.workSpareMaterials[index].checkSpareSpecCode = val.specSkuCode
    } else {
      if (!val) {
        dataList.value.workSpareMaterials[index].checkSpareSpecCode = ''
        dataList.value.workSpareMaterials[index].checkSpareSpec = ''
      }
    }

    const price = dataList.value.workSpareMaterials[index].overinsured ? val.overPrice : val.price
    if (dataList.value.workSpareMaterials[index].type === 1) {
      /**
       * 收支类型是商家承担
       * 将规格的金额填充到收取商家费用
       */
      dataList.value.workSpareMaterials[index].receiveFactoryPrice = `${price}`
    } else {
      /**
       * 收支类型是商家承担
       * 将规格的金额填充到平台承担费用
       */
      dataList.value.workSpareMaterials[index].price = `${price}`
    }
  }

  /**
   * 添加图片
   * @param {object} file - 文件
   * @param {number} index - 操作的表格行的索引
   */
  const getProImages = (file: UploadFile, index: number) => {
    if (!['image/png', 'image/jpg', 'image/jpeg'].includes(file.raw.type)) {
      imgType()
      return
    }
    if (dataList.value.workSpareMaterials[index].images.length >= 8) {
      onExceedNub()
      return
    }
    dataList.value.workSpareMaterials[index].images.push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
      id: null,
    })
  }
  const imgType = _.debounce(() => {
    ElMessage({
      type: 'error',
      message: '只能上传图片类型的文件',
    })
  }, 20)
  const onExceedNub = _.debounce(() => {
    ElMessage({
      showClose: true,
      message: '最多上传8个',
      type: 'error',
      duration: 2000,
    })
  }, 20)

  const onCancel = () => {
    emits('assign-dialog')
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    if (dataList.value.workSpareMaterials[rowIndex].images[imgIndex].id) {
      ElMessage({
        type: 'error',
        message: '禁止删除原本附件',
      })
      return
    }
    const imgs = dataList.value.workSpareMaterials[rowIndex].images.splice(imgIndex, 1)
    if (!dataList.value.workSpareMaterials[rowIndex].delImageIds) {
      dataList.value.workSpareMaterials[rowIndex].delImageIds = [imgs[0].id]
    } else {
      dataList.value.workSpareMaterials[rowIndex].delImageIds.push(imgs[0].id)
    }
  }

  /**
   * 收取商家费用输入框输入事件
   * @param {Event} e - input输入元素
   * @param {number} index - 表格操作的行的索引
   */
  const handleReceiveFactoryPriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].receiveFactoryPrice = (
      e.target as HTMLInputElement
    ).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 向服务商支付费用输入框输入事件
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlePayNetworkPricePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].payNetworkPrice = (e.target as HTMLInputElement).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  /**
   * 平台承担费用
   * @param {Event} e - Event
   * @param {number} index - 表格操作的行的索引
   */
  const handlePriceInput = (e: Event, index: number) => {
    checkNum(e)

    // 防止输入频繁输入会出现三位小数的问题
    dataList.value.workSpareMaterials[index].price = (e.target as HTMLInputElement).value

    // 限制金额的最大值为9999999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger(
      (e.target as HTMLInputElement).value,
      10,
    )
  }

  onMounted(async () => {
    if (partsId.value) {
      await getBeforeCheckOrderSpareDetailInfo(partsId.value)
      await getOrderSpareMaterialList(partsId.value)
    }
  })

  watch(
    props,
    async (value) => {
      if (value.checkDialog && value.partsId) {
        await getBeforeCheckOrderSpareDetailInfo(value.partsId)
        await getOrderSpareMaterialList(value.partsId)
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style lang="scss" scoped>
  :deep(.el-textarea__inner) {
    resize: none;
  }

  .singleAddress {
    :deep(.el-input) {
      width: 200px !important;
    }
  }

  :deep(.el-select__wrapper) {
    min-height: 28px !important;
    border-radius: 2px !important;
    font-size: 12px !important;
  }

  :deep(.el-input__wrapper) {
    height: 28px !important;
    font-size: 12px !important;
  }

  .header {
    display: flex;
    align-items: center;
    gap: 5px;

    .text {
      font-size: 16px;
      color: #000;
    }
  }

  .top_no {
    padding-bottom: 8px;
    font-size: 12px;
    color: #999;
  }

  .title_top {
    border-left: 2px solid #007cff;
    line-height: 14px;
    padding-left: 6px;
    margin-bottom: 8px;
  }

  .operation {
    display: flex;
    justify-content: center;
    align-items: center;

    .icon {
      cursor: pointer;
      margin: 0 6px;

      &:hover {
        transform: scale(1.2);
      }
    }
  }

  :deep(.el-table td.el-table__cell) {
    .el-input {
      .el-input__wrapper {
        height: 28px;
      }

      .el-input-group__prepend {
        padding: 0 2px;
      }
    }
  }

  :deep(.el-form-item) {
    margin-right: 15px;
    margin-bottom: 14px;

    .el-cascader .el-input {
      width: 220px;
    }

    .item-input {
      width: 200px;
    }

    .item-input-phone {
      width: 180px;
    }

    .item-input_w {
      width: 300px;
    }

    .el-form-item__label {
      font-size: 12px;
    }
  }

  :deep(.el-form-item .el-cascader .el-input) {
    width: 300px;
  }

  .form_sction {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;

    .look_text {
      font-size: 12px;
      white-space: nowrap;
      margin-right: 25px;
    }
  }

  .footer_remark {
    margin-top: 20px;

    .w_input {
      width: 600px;
      margin-left: 10px;
    }
  }

  :deep(.el-upload-list--picture-card) {
    display: flex;
    flex-wrap: nowrap;
    justify-content: flex-end;
    align-items: center;
    flex-direction: row-reverse;

    .el-upload {
      width: 40px;
      height: 40px;
      margin: 0 8px 0 0;
    }

    .el-upload-list__item {
      width: 40px;
      height: 40px;
      margin: 0 8px 0 0;
    }
  }

  :deep(.updata_pic) {
    display: flex;
    align-items: center;
    gap: 5px;

    .el-upload {
      &.el-upload--picture-card {
        width: 40px;
        height: 40px;
      }
    }

    .disf_ipc {
      display: flex;
      width: 40px;
      height: 40px;
      position: relative;
      margin-left: 6px;
      border: 1px solid #7f7f7f27;
      border-radius: 4px;
      box-sizing: border-box;
      overflow: hidden;

      .img {
        width: 100%;
        position: absolute;
        border-radius: 4px;
      }

      .item-actions {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
      }

      &:hover .item-actions {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #7f7f7f9d;
        opacity: 1;
        border-radius: 4px;

        .item-preview {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }

        .item-delete {
          margin: 0 4px;
          cursor: pointer;

          &:hover {
            transform: scale(1.2);
          }
        }
      }
    }
  }

  @import '../index.scss';
</style>
